//
//  SendView.swift
//  YueChat
//
//  Created by IMac on 2024/9/23.
//

import UIKit

enum AudioType: Int {
    case Cancel = 0
    case Word = 1
    case Send = 2
    case ReadyCancel = 3
    case ReadyWord = 4
    case ReadySend = 5
}

protocol SendViewDelegate: AnyObject {

    func didEmoView(isSelect:Bool)
    func didVoiceBtn()
    func didMoreBtn(isSelect:Bool)
    func didVoiceBtnSelect(isSelect:Bool)
    func didReturn(str:String)
    func didClearReply()
    func didKeyHeight(height:Float)
    func didNoticeToBlock()
}

class SendView: UIView ,YYTextViewDelegate{
    // 假设 MHAudioType 是一个枚举类型
    
//    var voiceBtnBlock: () -> Void = {}
    weak var delegate:SendViewDelegate?
    
    var chatType = Int()

    @IBOutlet weak var textBgView: UIView!
    @IBOutlet weak var voiceStatusBtn: UIButton!
//    @IBOutlet weak var voiceBtn: UIButton!
    @IBOutlet weak var moreBtn: UIButton!
    @IBOutlet weak var emjBtn: UIButton!
    @IBOutlet weak var textMsgField: UITextField!
    @IBOutlet weak var replyButton: UIButton!
    @IBOutlet weak var replyLabel: UILabel!
    @IBOutlet weak var replyName: UILabel!
    @IBOutlet weak var replyView: UIView!
    
    @IBOutlet weak var muteView: UIView!
    @IBOutlet weak var textViewTopConstraint: NSLayoutConstraint!
    
    var keyHeight = Float()
    
    var pan = UIPanGestureRecognizer()
    lazy var longGes: UILongPressGestureRecognizer = {
        let gesture = UILongPressGestureRecognizer(target: self, action: #selector(longAction(_:)))
        return gesture
    }()
    
    lazy var textView: YYTextView = {
        let textW: CGFloat = 124
        
        keyHeight = 21
        let frame = CGRect(x: 5, y: 5, width: textBgView.frame.size.width - textW, height: 45)
        let textView = YYTextView(frame: frame)
        textView.tintColor = kMainColor
        textView.font = UIFont.systemFont(ofSize: 17)
        textView.textColor = UIColor.black
        textView.delegate = self
        textView.returnKeyType = UIReturnKeyType.send
        
        textView.translatesAutoresizingMaskIntoConstraints = false

        return textView
    }()
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
//        self.msgRead.layer.masksToBounds = true
//        self.msgRead.layer.cornerRadius = 10
        self.frame = CGRect(x: 0, y: kScreenHeight - iPhoneXBottomHeight - 60, width: kScreenWidth, height: 60)
        textBgView.addSubview(textView)
//        voiceBtn.addGestureRecognizer(longGes)
    }
    
    // 显示取消菜单项
    func shoWcancelMenuItem() {
        let menuItem = UIMenuItem(title: "换行", action: #selector(cancelMenuItem))
        let menuController = UIMenuController.shared
        menuController.menuItems = [menuItem]
        menuController.setMenuVisible(false, animated: false)
    }

//    // 设置视图的隐藏状态
    func muteViewHidden(_ isHidden: Bool) {
        muteView.isHidden = isHidden
    }

    // 设置表情按钮的正常状态

    
    // MARK: - View Normalization Methods

    func emojViewNormal() {
        emjBtn.isSelected = false
        emjBtn.setImage(UIImage(named: "chat_expression_icon"), for: .normal)
    }

    func morejViewNormal() {
        moreBtn.isSelected = false
        moreBtn.setImage(UIImage(named: "chat_add_icon"), for: .normal)
    }

    func audioViewNormal() {
        voiceStatusBtn.isSelected = false
        voiceStatusBtn.setImage(UIImage(named: "chat_voice_grey_icon"), for: .normal)
    }
    

    @IBAction func emoClick(_ sender: Any) {
        emjBtn.isSelected = !emjBtn.isSelected
        if emjBtn.isSelected {
            emjBtn.setImage(UIImage.init(named: "chat_expression_blue_icon"), for: .normal)
        } else {
            emjBtn.setImage(UIImage.init(named: "chat_expression_icon"), for: .normal)
        }
        delegate?.didEmoView(isSelect: emjBtn.isSelected)
    }
    
    @IBAction func moreClick(_ sender: Any) {
        moreBtn.isSelected = true
        delegate?.didMoreBtn(isSelect: moreBtn.isSelected)
    }
    
    @IBAction func voiceClick(_ sender: Any) {
        voiceStatusBtn.isSelected = !voiceStatusBtn.isSelected
        delegate?.didVoiceBtnSelect(isSelect: voiceStatusBtn.isSelected)
        if voiceStatusBtn.isSelected {
            voiceStatusBtn.setImage(UIImage.init(named: "chat_voice_icon"), for: .normal)
        } else {
            voiceStatusBtn.setImage(UIImage.init(named: "chat_voice_grey_icon"), for: .normal)
        }
    }
    
    @IBAction func clearReplyClick(_ sender: Any) {

        textViewTopConstraint.constant = 10
        delegate?.didClearReply()
    }
    
    @objc func longAction(_ longGes: UILongPressGestureRecognizer) {

        delegate?.didVoiceBtn()
        
        guard longGes.state == .ended else { return }

            let location = longGes.location(in: self.voiceStatusBtn)
            let pointX = screenWidth / 2

            if location.x < 100 && location.y < -150 {
                let type = AudioType.Cancel // 假设MHAudioType是一个枚举
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kAudioNot_STATE), object: type.rawValue)
            } else if location.x > pointX && location.y < -150 {
                let type = AudioType.Word
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kAudioNot_STATE), object: type.rawValue)
            } else {
                let type = AudioType.Send
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kAudioNot_STATE), object: type.rawValue)
            }
        
//        let position = longGes.location(in: voiceBtn)
//        let pointX = UIScreen.main.bounds.width / 2
//        
//        if longGes.state == .ended {
//            if position.x < 100 && position.y < -150 {
//                let type = MHAudioType.Cancel
//                NotificationCenter.default.post(name: Notification.Name(FZ_EVENT_AUDIO_STATE), object: type.rawValue)
//            }else if position.x > pointX && position.y < -150 {
//                let type = MHAudioType.Word
//                NotificationCenter.default.post(name: Notification.Name(FZ_EVENT_AUDIO_STATE), object: type.rawValue)
//            }else{
//                let type = MHAudioType.Send
//                NotificationCenter.default.post(name: Notification.Name(FZ_EVENT_AUDIO_STATE), object: type.rawValue)
//            }
//        }else{
//            if position.x < 100 && position.y < -150 {
//                let type = MHAudioType.ReadyCancel
//                NotificationCenter.default.post(name: Notification.Name(FZ_EVENT_AUDIO_STATE), object: type.rawValue)
//            }else if position.x > pointX && position.y < -150 {
//                let type = MHAudioType.ReadyWord
//                NotificationCenter.default.post(name: Notification.Name(FZ_EVENT_AUDIO_STATE), object: type.rawValue)
//            }else{
//                let type = MHAudioType.ReadySend
//                NotificationCenter.default.post(name: Notification.Name(FZ_EVENT_AUDIO_STATE), object: type.rawValue)
//            }
//        }

    }
    
    func gestureRecognizer(_ gestureRecognizer: UIPanGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
    func setEmojText(_ emoJString: String) {
            textView.text = "\(textView.text ?? "")\(emoJString)"
            textView.selectedRange = NSRange(location: textView.text?.count ?? 0, length: 0)
        }
        
    func getTextFieldContent() -> String {
        let str = textView.text ?? ""
        textView.text = ""
        return str
    }
    
    func morejViewNomal() {
        moreBtn.isSelected = false
        // moreBtn.setImage(UIImage(named: "chat_add_icon"), for: .normal)
    }
        
    func textViewDidEndEditing(_ textView: YYTextView) {
    }

    func textViewShouldBeginEditing(_ textView: YYTextView) -> Bool {
//        shoWcancelMenuItem()
        if emjBtn.isSelected {
            emoClick(UIButton())
        }
        return true
    }

    func textView(_ textView: YYTextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let set = CharacterSet.whitespacesAndNewlines
        let nStr = (textView.text ?? "").trimmingCharacters(in: set)
        
        if textView.text?.count ?? 0 >= 2000 {
            MHAlert.showMessage(KLocalizedString("AlertSendMoreWordNum"))
            let maxLength = min(textView.text.count, 2000)
            let str = String(textView.text.prefix(maxLength))
            if text == "\n" {
                delegate?.didReturn(str: textView.text)
                textView.text = ""
                return false
            }
            return false
        }

        if text == "\n" {

            delegate?.didReturn(str: textView.text)
            textView.text = ""
            return false
        }

        if chatType == OsnIdType.group.rawValue, text == "@" {
            delegate?.didNoticeToBlock()
        }

        return true
    }

    @objc func cancelMenuItem() {
        let set = CharacterSet.whitespacesAndNewlines
        let nStr = (textView.text ?? "").trimmingCharacters(in: set)
        guard nStr.count > 0 else { return }
        let location = textView.selectedRange.location
        
//        let start = textView.text[..<textView.selectedTextRange!.start]
//        let end = textView.text[textView.selectedTextRange!.start...]
        
        let startRange = textView.selectedRange.location
        let start = String(textView.text.prefix(startRange))
//
//        
//        let endRange = Range(<#T##NSRange#>, in: <#T##String#>)
//        NSRange(location: textView.selectedRange.location, length: textView.text.count - textView.selectedRange.location)
        let end = textView.text.index(textView.selectedRange.description.startIndex, offsetBy: textView.text.count - textView.selectedRange.location)

        textView.text = "\(start)\n\(end)"
        textView.selectedRange = NSRange(location: location + 1, length: 0)
        if keyHeight <= 200 {
            keyHeight += 21
//            updateHeight()
        }
    }

    func onClickOverlayt() {
//        delegate?.didKeyHeight(height: keyHeight)
//        print("onClickOverlayonClickOverlay1")
//        cancelPreviousPerformRequestsWithTarget(self, selector: #selector(updateHeight), object: textView)
//        perform(#selector(updateHeight), with: textView, afterDelay: 0.05)
    }

    @objc func updateHeight() {
        print("onClickOverlayonClickOverlay")
//        keyHeightBlock?(keyHeight)
    }

    private func textViewDidChange(_ textView: UITextView) {
//        let att = textView.attributedText
//        let height = heightForAttributeText(att!, maxWidth: textView.frame.width - 10)
//        let height2 = textView.frame.height - 20
//        if abs(height - height2) > 13 {
//            keyHeight = Float(max(min(height, 200), 25))
//            onClickOverlayt()
//        }
    }

    func heightForAttributeText(_ attributeText: NSAttributedString, maxWidth: CGFloat) -> CGFloat {
        let container = YYTextContainer(size: CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude))
        container.maximumNumberOfRows = 0
        let layout = YYTextLayout(container: container, text: attributeText)
        return layout!.textBoundingSize.height
    }
    

}
